package com.maple.common.utils

import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager

/**
 * Tip:USB 设备通信
 *
 * 支持通过 USB Host API 与 USB 设备通信。常见的应用场景包括连接 USB 打印机、扫码枪等
 *
 * 需要权限
 * <uses-feature android:name="android.hardware.usb.host"/>
 * <uses-permission android:name="android.permission.USB_PERMISSION"/>
 *
 * Create by SeVen on 2025/4/2 9:32
 *
 */
class UsbHelper(context: Context) {

    private val usbManager: UsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager

    private var usbDevice: UsbDevice? = null
    private var usbDeviceConnection: UsbDeviceConnection? = null
    private var usbEndpoint: UsbEndpoint? = null

    /**
     * 链接USB设备
     * Connect usb device
     *
     * @param device
     * @return
     */
    fun connectUsbDevice(device: UsbDevice): Boolean {
        this.usbDevice = device
        val usbInterface: UsbInterface = device.getInterface(0)
        usbEndpoint = usbInterface.getEndpoint(0)

        usbDeviceConnection = usbManager.openDevice(usbDevice)
        if (usbDeviceConnection != null && usbDeviceConnection?.claimInterface(
                usbInterface,
                true
            ) == true
        ) {
            return true
        }
        return false
    }

    /**
     * 发送数据
     * Send data
     *
     * @param data
     */
    fun sendData(data: ByteArray) {
        if (usbDeviceConnection != null && usbEndpoint != null) {
            usbDeviceConnection?.bulkTransfer(usbEndpoint, data, data.size, 1000)
        }
    }

    /**
     * 读取数据
     * Read data
     */
    fun readData(): ByteArray? {
        if (usbDeviceConnection != null && usbEndpoint != null) {
            val buffer = ByteArray(1024)
            val length: Int =
                usbDeviceConnection!!.bulkTransfer(usbEndpoint, buffer, buffer.size, 1000)
            if (length > 0) {
                val result = ByteArray(length)
                System.arraycopy(buffer, 0, result, 0, length)
                return result
            }
        }
        return null
    }

    /**
     * 关闭连接
     * Close connection
     *
     */
    fun closeConnection() {
        usbDeviceConnection?.close()
    }
}